package com.yvon.maple.service.base.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.ContentType;
import com.yvon.boot.common.result.GlobalException;
import com.yvon.maple.service.base.entity.FileInfo;
import com.yvon.maple.service.base.ffmpeg.FfmpegUtils;
import com.yvon.maple.service.base.service.VideoService;
import com.yvon.maple.service.base.util.FileUtils;
import com.yvon.maple.service.base.util.ThreadPoolExecutorUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Slf4j
@Service
public class VideoServiceImpl implements VideoService {
    @Override
    public String mediaFileToM3u8(MultipartFile file, FileInfo fileInfo) {
        if (file.isEmpty()) {
            throw new RuntimeException("未发现文件");
        }
        log.info("开始解析视频");
        long start = System.currentTimeMillis();
        //临时目录创建
        String path = new File(System.getProperty("user.dir")).getAbsolutePath();
        String tempFilePath = path + "/" + fileInfo.getId() + "/";
        if (!FileUtil.exist(tempFilePath)) {
            FileUtil.mkdir(tempFilePath);
        }
        String filePathName = tempFilePath + fileInfo.getFileName();
        File dest = new File(filePathName);
        try {
            file.transferTo(dest);
        }catch (Exception e){
            log.error("视频转m3u8格式存在异常，异常原因e:{}",e.getMessage());
        }
        long end = System.currentTimeMillis();
        log.info("临时文件上传成功......耗时：{} ms", end - start);
        String m3u8 = localFileToM3u8(filePathName);
        fileInfo.setFileName(FileUtil.getName(m3u8));
        fileInfo.setContentType("hls");
        return m3u8;
    }

    public String localFileToM3u8(String filePathName) {
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> FfmpegUtils.videoToMp4(filePathName), ThreadPoolExecutorUtils.pool);
        CompletableFuture<String> completableFutureTaskHls = completableFuture.thenApplyAsync((String string)->{
            log.info("第一步：视频整体转mp4,成功！");
            String ts = FfmpegUtils.mp4ToTs(string);
            log.info("第二步：视频整体转码ts,成功！");
            String spilt = FfmpegUtils.tsSpilt(ts);
            log.info("第三步：ts切片,成功！");
            return spilt;
        }, ThreadPoolExecutorUtils.pool);

        //获取执行结果
        try {
            String m3u8FileName = completableFutureTaskHls.get();
            log.info("获取最终执行结果: [{}]", m3u8FileName);
            return m3u8FileName;
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        throw new GlobalException("切片失败");
    }
}
